<?php
require_once(dirname(__FILE__)."/config.php");

if(!defined('PP_OPEN') || !defined('PP_TYPE') || !defined('PP_KEY'))
{
	ShowMsg('系统没有开启通行证功能！','-1');exit();
}


if(!PP_OPEN || PP_TYPE != 'server')
{
	ShowMsg('系统没有开启通行证功能！','-1');exit();
}

if(md5($action.$userdb.$forward.PP_KEY) != $verify)
{
	ShowMsg('安全检验失败，请检查通行证设置是否正确！','-1');exit();
}

parse_str(StrCode($userdb,'DECODE'),$userdb);
if (!$forward || strpos($forward,'index_do.php') !== false)
{
	$forward = PP_API;
}

$timestamp = time();
$loginip = GetIP();
if($action=='login')
{
	foreach($userdb as $key => $val)
	{
		$userdb[$key] = addslashes($val);
	}
	
	if(!$userdb['time'] || !$userdb['username'] || !$userdb['password'])
	{
		ShowMsg('数据检验失败，缺少参数！lack_data');exit();
	}
	if($timestamp > $userdb['time']+3600)
	{
		ShowMsg('数据检验失败，无效数据！expired_error');exit();
	}

	$members = $dsql->GetOne("SELECT `mid`,`userid`,`pwd`,`uname` FROM #@__member WHERE userid='$userdb[username]' ");

	if(!is_array($members))
	{
		//会员的默认金币
		$row = $dsql->GetOne("SELECT `money`,`scores` FROM `#@__arcrank` WHERE `rank`='10' ");
		$scores = is_array($row) ? $row['scores'] : 0;
		$money = is_array($row) ? $row['money'] : 0;
		$logintime = $jointime = $timestamp;
		$joinip = $loginip;
		
		$res = $dsql->ExecuteNoneQuery("INSERT INTO #@__member SET `mtype`='个人',`userid`='$userdb[username]',`pwd`='$userdb[password]',`uname`='$userdb[username]',`sex`='男' ,`rank`='10',`uprank`='0',`money`='$money', `upmoney`='0', `email`='$userdb[email]', `scores`='$scores', `matt`='0', `face`='',`safequestion`='0',`safeanswer`='', `jointime`='$jointime',`joinip`='$joinip',`logintime`='$logintime',`loginip`='$loginip';");
		if($res)
		{
			$mid = $dsql->GetLastID();
			$data = array();
			foreach($data as $val) $dsql->ExecuteNoneQuery($val);
		}
	}
	else
	{
		$mid = $members['mid'];
		$sqladd = '';
		if($members['userid'] != $userdb['username'])
		{
			$sqladd .= " userid='$userdb[username]',";
		}
		if($members['pwd'] != $userdb['password'])
		{
			$sqladd .= " `pwd`='$userdb[password]', ";
		}
		$dsql->ExecuteNoneQuery("UPDATE `#@__member` SET $sqladd `logintime`='$timestamp',`loginip`='$loginip' WHERE `mid`='$mid' ");
	}
	
	$cfg_ml->PutLoginInfo($mid);
	header("Location:$forward");exit();
}
elseif($action=='quit')
{
	$cfg_ml->ExitCookie();
	header("Location:$forward");exit();
}

function StrCode($string,$action='ENCODE')
{
	$action != 'ENCODE' && $string = base64_decode($string);
	$code = '';
	$key  = substr(md5($_SERVER['HTTP_USER_AGENT'].PP_KEY),8,18);
	$keylen = strlen($key);
	$strlen = strlen($string);
	for($i=0;$i < $strlen;$i++)
	{
		$k		= $i % $keylen;
		$code  .= $string[$i] ^ $key[$k];
	}
	return ($action!='DECODE' ? base64_encode($code) : $code);
}
?>